package com.b2c.erp.controller.api;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.b2c.common.utils.MD5Utils;
import com.b2c.entity.ManageUserEntity;
import com.b2c.entity.api.ApiResultEnum;
import com.b2c.entity.enums.UserStateEnums;
import com.b2c.entity.result.ResultVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.erp.controller.api.response.UserInfo;
import com.b2c.interfaces.WmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.b2c.entity.DataRow;
import com.b2c.erp.controller.api.response.LoginResp;
import com.b2c.entity.api.ApiResult;

@Slf4j
@RestController
@RequestMapping("/api/v1")
public class LoginApiController {
    private final String key = "key0123412345678";
    private final String IV = "key0123412345678";
    @Autowired
    private WmsUserService manageUserService;
    @RequestMapping(value = "/manage_user_login", method = RequestMethod.POST)
    public ApiResult<LoginResp> userLogin(@RequestBody DataRow reqData) throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String userName = reqData.getString("username");
        String userPwdO = reqData.getString("password");

        //解密前端传过来的加密密码
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ASCII"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = Base64.decodeBase64(userPwdO);//先用bAES64解密
        String userPwd =new String(cipher.doFinal(encrypted1));

        ResultVo<ManageUserEntity> result = manageUserService.userLogin(userName, userPwd);
        if (result.getCode() == 0) {
            ManageUserEntity user = result.getData();
            String name = StringUtils.isEmpty(user.getUserName()) ? user.getTrueName() : user.getUserName();

            int expires = 7 * 24 * 60 * 60 * 1000;//60分钟
            Date expDate = new Date(System.currentTimeMillis() + expires);
            String secret = DataConfigObject.getInstance().getJwtSecret();
            Algorithm algorithm = Algorithm.HMAC256(secret);
            Map<String, Object> mapObj = new HashMap<>();
            mapObj.put("userId", user.getId());
            String token = JWT.create()
                    .withIssuer("auth0").withHeader(mapObj)
                    .withClaim("userId", user.getId())
                    .withClaim("userName", name)
                    .withExpiresAt(expDate).withNotBefore(new Date())
                    .sign(algorithm);
            LoginResp loginResp = new LoginResp();
            loginResp.setUserInfo(new UserInfo(name,name,""));
            loginResp.setRoles("admin");
            loginResp.setToken(token);
            loginResp.setPermission(new String[]{"sys_crud_btn_add","sys_crud_btn_export","sys_menu_btn_add","sys_menu_btn_edit","sys_menu_btn_del","sys_role_btn1"});
            return new ApiResult<>(ApiResultEnum.SUCCESS.getIndex(), "成功", loginResp);
        }else return new ApiResult<>(result.getCode(),result.getMsg());

    }

    @RequestMapping("/user/getUserInfo")
    public ApiResult<LoginResp> getUserInfo(){
        Integer userId= DataConfigObject.getInstance().getLoginUserId();
        ManageUserEntity user = manageUserService.getWmsManageUser(userId);
        UserInfo info = new UserInfo(user.getUserName(),user.getTrueName(),"");
        LoginResp loginResp = new LoginResp();
        loginResp.setUserInfo(info);
        loginResp.setRoles("admin");
//        loginResp.setToken(token);
        loginResp.setPermission(new String[]{"sys_crud_btn_add","sys_crud_btn_export","sys_menu_btn_add","sys_menu_btn_edit","sys_menu_btn_del","sys_role_btn1"});
        return new ApiResult<>(ApiResultEnum.SUCCESS,loginResp);
    }
}
